package com.aivin.buildsrc.myactions;

import com.aivin.buildsrc.bean.Md5SaveBean;
import com.aivin.buildsrc.mytask.FileMd5CheckkTask;
import com.aivin.buildsrc.tool.CalcMD5;
import com.aivin.buildsrc.tool.WkLog;
import org.gradle.api.Action;
import org.gradle.api.Project;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;

public class Md5CheckAction implements Action {
    private Project project ;
    private FileMd5CheckkTask task ;
    private Map<String , Md5SaveBean> md5Info = new HashMap<>() ;

    public Md5CheckAction(Project project ,FileMd5CheckkTask task){
        this.project = project ;
        this.task = task ;
    }


    @Override
    public void execute(@Nullable Object o) {
        md5Info.clear();
        boolean isEableMd5Check = task.getFileMd5Check() ;

        if(!isEableMd5Check){
            WkLog.showMsg("isEableMd5Check is false ,return ...");
        }

        processPgroject(project );
        saveInfoToLocal();
        WkLog.showMsg(" save finished ...") ;
    }

    private void processPgroject(Project project  ) {
        int size = project.getChildProjects().size() ;
        if (size  > 1) {
            project.getChildProjects().forEach((key, value) -> {
                processPgroject( value  ) ;
            });
        } else {
            File file = new File(project.getName()) ;
            CalcMD5.getAllFiles(file.getAbsolutePath() ,md5Info) ;
        }
    }


    private void saveInfoToLocal(){
        File file = new File("c://wkfileMd5check_"+System.currentTimeMillis()+".txt") ;
        for (Object object : md5Info.keySet()) {
            String key = (String) object;
            Md5SaveBean bean =   md5Info.get(key);
            if(bean.count>1){
                String messgeStr = "\r\nfind same files-> "+ key +"  "+ bean.count+"   "+bean.name;
                WkLog.showMsg( messgeStr);
                try {
                    FileWriter writer = new FileWriter(file.getAbsoluteFile(), true);
                    writer.write(messgeStr + "\r\n");
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    }





}
